<template>
    <a-form ref="formRef" :model="form" :label-col="{ span: 2 }" :wrapper-col="{ span: 20 }" layout="horizontal" autocomplete="off">
        <a-form-item label="密码" :rules="rules.password" name="password">
            <a-input-password v-model:value="form.password" placeholder="请输入密码" />
        </a-form-item>
        <a-form-item label="重复密码" :rules="rules.repassword" name="repassword">
            <a-input-password v-model:value="form.repassword" placeholder="请再次输入密码" />
        </a-form-item>
    </a-form>
    <div class="btn-container">
        <a-button type="primary" @click="onSave">保存</a-button>
        <a-button type="primary" danger @click="onClose">关闭</a-button>
    </div>
</template>
<script setup>
import { ref, reactive } from 'vue'
import { PasswordRegular } from '@iframe/tools/utils/regular'
import { rePass } from '/@/api/System/User'
import { SUCCESS_CODE } from '@iframe/tools/axios/axios'
import { notice } from '@iframe/tools/components/index'

const formRef = ref()
const form = reactive({})
const emits = defineEmits(['close'])
const repasswordChecked = (rule, value) => {
    if (value === form.password) {
        return Promise.resolve()
    }
    return Promise.reject('两次密码不一致')
}
const rules = reactive({
    password: [
        { required: true, message: '请输入密码' },
        { pattern: PasswordRegular, message: '密码必须以字母开头，包括数字的8-20位字符串' }
    ],
    repassword: [{ required: true, message: '请输入重复密码' }, { validator: repasswordChecked }]
})

const onSave = () => {
    formRef.value
        .validate()
        .then(params => {
            rePass({ password: params.password }).then(result => {
                if (result.code === SUCCESS_CODE) {
                    notice.success('修改密码成功')
                    formRef.value.resetFields()
                }
            })
        })
        .catch(err => {
            console.warn(err)
        })
}

const onClose = () => {
    emits('close')
}
</script>

<style lang="less" scoped>
.btn-container {
    padding-left: 200px;
    :deep(.ant-btn) {
        margin: 5px;
    }
}
</style>
